#include "xld_btdt.h"

#ifdef __XLD_BTDT__

// https://github.com/XieLazyDog/ValuePack.git

uint8_t XldBtdt_CheckRxBuf(XldBtdt* dt)
{
	uint16_t i = 1;
	uint8_t checkSum = 0;
	for(	; i < dt->rxCnt - 1; i++)
	{
		checkSum += dt->rxBuf[i];
	}
	if(checkSum == dt->rxBuf[dt->rxCnt - 1])
	{
		return 0;
	}
	return 1;
}

void XldBtdt_PackAndTransmit(XldBtdt* dt, void* buf, int16_t len)
{
	dt->txBuf[0] = XLD_BTDT_FRAME_HEAD;
	
	uint16_t i = 0;
	uint8_t checkSum = 0;
	for(	; i < len; i++)
	{
		dt->txBuf[i + 1] = ((uint8_t*)buf)[i];
		checkSum += ((uint8_t*)buf)[i + 1];
	}
	dt->txBuf[1 + len] = checkSum;
	dt->txBuf[1 + len + 1] = XLD_BTDT_FRAME_TAIL;

	dt->txCnt = len + 3;
	XldBtdt_Transmit(dt);
}

void XldBtdt_ReceiveByte(XldBtdt* dt, uint8_t recvData)
{

	if(XLD_BTDT_FRAME_HEAD == recvData)
	{
		dt->rxCnt = 0;
	}

	if(XLD_BTDT_FRAME_TAIL == recvData)
	{
		if(0 == XldBtdt_CheckRxBuf(dt))
		{
			XldBtdt_UnpackRxBuf(dt);
		}
	}
	// 读取数据到缓冲区中
	dt->rxBuf[dt->rxCnt++] = recvData;
	dt->rxCnt %= XLD_BTDT_BUFFER_SIZE;

}

#endif // __XLD_BTDT__



